package com.example.thirdhomework

import android.annotation.SuppressLint
import android.os.Bundle
import android.os.Handler
import android.util.Log
import android.widget.Button
import android.widget.TextView
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat

class MainActivity5 : AppCompatActivity() {
    var seconds = 0
    var running = false
    var wasrunning = false
    @SuppressLint("CutPasteId")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_main5)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }
//        恢复状态
        if (savedInstanceState != null){
            seconds = savedInstanceState.getInt("seconds")
            running = savedInstanceState.getBoolean("running")
            wasrunning = savedInstanceState.getBoolean("wasrunning")
        }
        runTimer()
        val start = findViewById<Button>(R.id.button_start)
        start.setOnClickListener{
            running = true
        }
        val stop = findViewById<Button>(R.id.button_stop)
        stop.setOnClickListener{
            running = false
        }
        val restart = findViewById<Button>(R.id.button_restart)
        restart.setOnClickListener{
            running = true
            seconds = 0
        }
    }
    fun runTimer(){
        val handler = Handler()
        val runnable = object:Runnable{
            @SuppressLint("DefaultLocale")
            override fun run(){
                val hours = seconds/3600
                val minutes = (seconds % 3600)/60
                val secs = seconds % 60
                val timer = findViewById<TextView>(R.id.textView_timer)
                timer.text = String.format("%02d:%02d:%02d",hours,minutes,secs)
                if(running){
                    seconds++
                }
                handler.postDelayed(this,1000)
            }
        }
        handler.post(runnable)
    }
//    状态的保存
    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        Log.d("life cycle","onSaveInstanceState")
        outState.putInt("seconds",seconds)
        outState.putBoolean("running",running)
        outState.putBoolean("wasrunning",running)
//        进入后台时调用的保持状态
    }
//    override fun onDestory(){
//        super.onDestroy()
//        Log.d("life cycle","onDestroy")
//    }
}